import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'

// 持久化相关配置
const STORAGE_KEY = 'vue3-demo-counter'
const STORAGE_VERSION = '1.0.0'

// 持久化数据结构
interface PersistedData {
  count: number
  lastUpdated: string
  version: string
}

export const useCounterStore = defineStore('counter', () => {
  // 基础状态
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)

  // 持久化状态
  const isPersistenceEnabled = ref(true)
  const lastUpdated = ref<string>('')

  // 从localStorage加载数据
  const loadFromStorage = (): boolean => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (!stored) return false

      const data: PersistedData = JSON.parse(stored)

      // 版本检查
      if (data.version !== STORAGE_VERSION) {
        console.warn('存储版本不匹配，清除旧数据')
        localStorage.removeItem(STORAGE_KEY)
        return false
      }

      // 恢复数据
      count.value = data.count || 0
      lastUpdated.value = data.lastUpdated || ''

      console.log('✅ 从本地存储恢复数据:', data)
      return true
    } catch (error) {
      console.error('❌ 加载持久化数据失败:', error)
      return false
    }
  }

  // 保存到localStorage
  const saveToStorage = () => {
    if (!isPersistenceEnabled.value) return

    try {
      const data: PersistedData = {
        count: count.value,
        lastUpdated: new Date().toISOString(),
        version: STORAGE_VERSION,
      }

      localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
      lastUpdated.value = data.lastUpdated
      console.log('💾 数据已保存到本地存储')
    } catch (error) {
      console.error('💾 保存持久化数据失败:', error)
    }
  }

  // 清除持久化数据
  const clearStorage = () => {
    try {
      localStorage.removeItem(STORAGE_KEY)
      lastUpdated.value = ''
      console.log('🗑️ 持久化数据已清除')
    } catch (error) {
      console.error('🗑️ 清除持久化数据失败:', error)
    }
  }

  // 操作方法
  function increment() {
    count.value++
  }

  function decrement() {
    count.value--
  }

  function reset() {
    count.value = 0
  }

  // 设置持久化开关
  function togglePersistence() {
    isPersistenceEnabled.value = !isPersistenceEnabled.value
    if (isPersistenceEnabled.value) {
      saveToStorage()
    } else {
      clearStorage()
    }
  }

  // 完全重置
  function fullReset() {
    count.value = 0
    lastUpdated.value = ''
    clearStorage()
    console.log('🔄 完全重置完成：计数器、本地存储全部清空')
  }

  // 获取存储大小
  const getStorageSize = computed(() => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      return stored ? new Blob([stored]).size : 0
    } catch {
      return 0
    }
  })

  // 初始化时加载数据
  loadFromStorage()

  // 监听状态变化，自动保存
  watch(count, () => {
    if (isPersistenceEnabled.value) {
      saveToStorage()
    }
  })

  return {
    // 状态
    count,
    doubleCount,
    isPersistenceEnabled,
    lastUpdated,
    getStorageSize,
    // 操作方法
    increment,
    decrement,
    reset,
    // 持久化方法
    loadFromStorage,
    saveToStorage,
    clearStorage,
    togglePersistence,
    fullReset,
  }
})
